package org.dslintegration.merge.km3.exporter;

import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.net.URL;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import org.dslintegration.merge.km3.core.Metamodel;
import org.dslintegration.metamodelmerge.Activator;
import org.eclipse.core.runtime.FileLocator;
import org.eclipse.core.runtime.Path;
import org.osgi.framework.Bundle;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

public class KM3MetamodelExporter {

	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static String export(Metamodel metamodel) throws IOException, TemplateException {

		Map datamodel = new HashMap();
		datamodel.put("metamodel", metamodel);

		Configuration cfg = new Configuration();
		try {
			cfg.setDirectoryForTemplateLoading(findTemplateFile());
		} catch (NullPointerException ex) {
			cfg.setDirectoryForTemplateLoading(new File(KM3MetamodelExporter.class.getResource("").getPath()));
		}

		Template tpl = cfg.getTemplate("km3.template");
		StringWriter writer = new StringWriter();
		tpl.process(datamodel, writer);

		return writer.toString();
	}

	protected static File findTemplateFile() {
		Bundle bundle = Activator.getDefault().getBundle();
		Path path = new Path("src/org/dslintegration/merge/km3/exporter"); //$NON-NLS-1$
		URL url = FileLocator.find(bundle, path, Collections.EMPTY_MAP);
		URL fileUrl = null;
		try {
			fileUrl = FileLocator.toFileURL(url);
		} catch (IOException e) {
			// Will happen if the file cannot be read for some reason
			e.printStackTrace();
		}
		File file = new File(fileUrl.getPath());
		return file;
	}
}
